#include "adc.h"

uint16_t dma_Value[amd_BufferSize];

void adc_init(void)
{
	ADC_InitTypeDef Adc_Value;
	DMA_InitTypeDef Dma_Value;
	
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1 | RCC_APB2Periph_AFIO,ENABLE);
	RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA1,ENABLE);
	
	ADC_RegularChannelConfig(ADC1,ADC_Channel_8,1,ADC_SampleTime_55Cycles5);
	ADC_RegularChannelConfig(ADC1,ADC_Channel_9,2,ADC_SampleTime_55Cycles5);
	
	Adc_Value.ADC_ContinuousConvMode = DISABLE;
	Adc_Value.ADC_DataAlign = ADC_DataAlign_Right;
	Adc_Value.ADC_ExternalTrigConv = ADC_ExternalTrigConv_None;
	Adc_Value.ADC_Mode = ADC_Mode_Independent;
	Adc_Value.ADC_NbrOfChannel = amd_BufferSize;
	Adc_Value.ADC_ScanConvMode = ENABLE;
	ADC_Init(ADC1,&Adc_Value);
	
//	ADC_Cmd(ADC1,ENABLE);
	
	Dma_Value.DMA_BufferSize = amd_BufferSize;
	Dma_Value.DMA_DIR = DMA_DIR_PeripheralSRC;
	Dma_Value.DMA_M2M = DMA_M2M_Disable;
	Dma_Value.DMA_MemoryBaseAddr = (uint32_t)dma_Value;
	Dma_Value.DMA_MemoryDataSize = DMA_MemoryDataSize_HalfWord;
	Dma_Value.DMA_MemoryInc = DMA_MemoryInc_Enable;
	Dma_Value.DMA_Mode = DMA_Mode_Normal;
	Dma_Value.DMA_PeripheralBaseAddr = (uint32_t)&ADC1->DR;
	Dma_Value.DMA_PeripheralDataSize = DMA_PeripheralDataSize_HalfWord;
	Dma_Value.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
	Dma_Value.DMA_Priority = DMA_Priority_Medium;
	DMA_Init(DMA1_Channel1,&Dma_Value);
	
  DMA_Cmd(DMA1_Channel1, ENABLE);  
	ADC_DMACmd(ADC1, ENABLE);
	ADC_Cmd(ADC1, ENABLE);
  
	//ADCУ׼
	ADC_ResetCalibration(ADC1);
	while(ADC_GetResetCalibrationStatus(ADC1));
	ADC_StartCalibration(ADC1);
	while(ADC_GetCalibrationStatus(ADC1));
}

void get_adc_value(uint16_t *data)
{
  DMA_Cmd(DMA1_Channel1, DISABLE);
  DMA_SetCurrDataCounter(DMA1_Channel1,amd_BufferSize);
  DMA_Cmd(DMA1_Channel1, ENABLE);
    
  ADC_SoftwareStartConvCmd(ADC1, ENABLE);
    
  while (DMA_GetFlagStatus(DMA1_FLAG_TC1) == RESET);
  DMA_ClearFlag(DMA1_FLAG_TC1);
}
